package service

import (
	"database/sql"
	"ollama-go/dto"
	"ollama-go/entity"
	"ollama-go/query"
	"ollama-go/vo"

	"github.com/androidsr/sc-go/model"
	"github.com/androidsr/sc-go/sbuilder"
	"github.com/androidsr/sc-go/sc"
	"github.com/androidsr/sc-go/sgorm"
)

var (
	ollamaCollectionService *OllamaCollectionService
)

type OllamaCollectionService struct {
}

func NewOllamaCollectionService() *OllamaCollectionService {
	if ollamaCollectionService == nil {
		ollamaCollectionService = new(OllamaCollectionService)
	}
	return ollamaCollectionService
}

// 使用id获取数据
func (m OllamaCollectionService) Get(id string) *vo.OllamaCollectionVO {
	data := new(entity.OllamaCollection)
	data.Uuid = id
	err := sgorm.DB.GetOne(data)
	if err != nil {
		return nil
	}
	return sc.Copy[vo.OllamaCollectionVO](data)
}

// 使用id获取数据
func (m OllamaCollectionService) GetTenantId(name string) string {
	s := `select a.cmetadata ->> 'tenantId' as tenantId from ollama_collection a where a.name = ?`
	var tenantId sql.NullString
	err := sgorm.DB.Raw(s, name).Scan(&tenantId).Error
	if err != nil {
		return ""
	}
	return tenantId.String
}

// 更新数据
func (m OllamaCollectionService) UpdateById(dto *dto.OllamaCollectionDTO) error {
	dbEntity := new(entity.OllamaCollection)
	dbEntity.Uuid = dto.Uuid
	sgorm.DB.GetOne(dbEntity)
	sc.CopyTo(dto, dbEntity)
	err := sgorm.DB.UpdateById(dbEntity).Error
	return err
}

// 删除数据
func (m OllamaCollectionService) DeleteById(id string) error {
	err := NewOllamaEmbeddingService().DeleteByCollectionId(id)
	if err != nil {
		return err
	}
	err = sgorm.DB.Delete(new(entity.OllamaCollection), "uuid = ?", id).Error
	if err != nil {
		return err
	}
	return nil
}

// 分页列表查询
func (m OllamaCollectionService) QueryPage(query *query.OllamaCollectionQueryDTO) *model.PageResult {
	sql := `select * from ollama_collection a `
	data := make([]entity.OllamaCollection, 0)
	b := sbuilder.StructToBuilder(query, sql)
	sql, values := b.Build()
	return sgorm.DB.SelectPage(&data, query.BaseQueryDTO.Page, sql, values...)
}

// 分页下拉查询
func (m OllamaCollectionService) QueryList(query *model.SelectQueryDTO) *model.PageResult {
	sql := `select a.uuid as value, a.name as label from ollama_collection a where 1=1 `
	data := make([]model.SelectVO, 0)
	b := sbuilder.Builder(sql)
	b.Like("CONCAT(a.uuid,a.name)", query.Label)
	tenantId := query.Vars["tenantId"]
	delete(query.Vars, "tenantId")
	for k, v := range query.Vars {
		b.Eq(k, v)
	}
	b.Multiple().Ors(b.In("a.uuid", query.Selected))
	b.Multiple().Ands(b.Eq("a.cmetadata ->> 'tenantId'", tenantId), b.Or().IsNull("a.cmetadata ->> 'tenantId'"))
	sql, values := b.Build()
	return sgorm.DB.SelectPage(&data, &query.Page, sql, values...)
}
